<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" @reset="resetData">
      <el-col :span="8" :xs="24" v-show="$permiss[454]">
        <el-form-item :label="$t('所属租户')" prop="type">
          <el-select style="width: 100%" v-model="page.adminUserId" clearable>
            <el-option v-for="tenant in tenantList" :key="tenant.adminUserId"
                       :value="tenant.adminUserId" :label="tenant.adminName"/>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="name">
          <el-input v-model="page.name"/>
        </el-form-item>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone"/>
        </el-form-item>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('免审状态')" prop="type">
          <!--是否免审核（0免审核，1需审核）-->
          <el-select style="width: 100%" v-model="page.avoidAudit" clearable>
            <el-option :label="$t('是')" :value="1"></el-option>
            <el-option :label="$t('否')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <!-- 条件第二行 -->
      <el-col :span="8" :xs="24" v-show="$permiss[453]">
        <el-form-item :label="$t('渠道')" prop="type">
          <!--1业务拉黑，2导入，3灰转黑-->
          <el-select style="width: 100%" v-model="page.channelName" clearable>
            <el-option v-for="channel in channelList" :key="channel" :value="channel"
                       :label="channel">

            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('状态')">
          <el-select style="width: 100%" v-model="page.valid" clearable>
            <el-option :label="$t('有效')" :value="1"></el-option>
            <el-option :label="$t('无效')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <!-- 条件第三行 -->
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('加入时间') + ':'" prop="timeValue">
          <el-date-picker
              v-model="page.timeValue"
              style="width: 100%"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="~"
              unlink-panels
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>

    <el-card shadow="never" style="margin-top: 10px">
      <div class="upButtonBg">
        <el-upload style="margin-right: 10px"
                   action="#"
                   ref="upload"
                   :show-file-list="false"
                   accept=".xls,.xlsx"
                   :http-request="uploadChange"
                   :before-upload="beforeAvatarUpload"
        >
          <el-button type="primary" v-show="$permiss[455]"> {{ $t('导入') }}</el-button>
        </el-upload>
        <el-upload style="margin-right: 10px"
                   action="#"
                   ref="upload"
                   :show-file-list="false"
                   accept=".xls,.xlsx"
                   :http-request="clearRepeat"
                   :before-upload="beforeAvatarUpload"
        >
          <el-button type="primary" v-show="$permiss[456]">{{ $t('数据去重') }}</el-button>
        </el-upload>
        <el-button @click="downLoanModel" type="primary" v-show="$permiss[455]">{{ $t('下载数据模版') }}</el-button>
      </div>
      <!--表单数据-->
      <Table row-key="id" :table-data="tableData" :page="page" :tableColumn="tableColumn"
             :loading="loading"
             @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange">
        <!--        <template slot="phone" slot-scope="{row}">-->
        <!--          <span v-show="row.phone">{{ '****' + row.phone.substr(row.phone.length - 4,4) }}</span>-->
        <!--        </template>-->
        <!--        <template slot="idCard" slot-scope="{row}">-->
        <!--          <span v-show="row.card">{{ '****' + row.card.substr(row.card.length - 4,4) }}</span>-->
        <!--        </template>-->
        <!--是否免审核（1是，0否）-->
        <template slot="avoidAudit" slot-scope="scope">
          {{ scope.row.avoidAudit === 0 ? $t('否') : $t('是') }}
        </template>
        <template slot="valid" slot-scope="{row}">
          {{ row.valid === 1 ? $t('有效') : $t('无效') }}
        </template>
      </Table>
    </el-card>
  </div>

</template>

<script>
import {dateFormatSection, defaultTimeDate} from "@/utils/tools";
import {selectTenant} from "@/api/system";
import {selectChannelName, addWhiteListCsv, selectRepeatWhitelist, fetchWhitelistList} from "@/api/channel";

export default {
  name: 'whiteList',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        name: '',
        phone: '',
        channelName: "", //渠道名称
        timeValue: defaultTimeDate(30)
      },
      loading: false,
      tenantList: [], //租户列表
      channelList: [],//下拉渠道列表
      tableData: [],
      tableColumn: [
        {label: this.$t('姓名'), prop: 'name', align: "center"},
        {label: this.$t('手机号码'), prop: 'phone', align: "center",},
        {label: this.$t('身份证号码'), prop: 'card', align: "center",},
        // {label: this.$t('是否免审核'), prop: 'avoidAudit', align: "center"},
        {label: this.$t('渠道'), prop: 'channelName', align: "center"},
        {label: this.$t('操作人'), prop: 'inputName', align: 'center'},
        {label: this.$t('加入时间'), prop: 'insertTime', align: "center", minWidth: 150},
        {label: this.$t('状态'), prop: 'valid', align: "center", slot: 'valid'},
        {label: this.$t('是否免审核'), prop: 'avoidAudit', align: "center", slot: 'avoidAudit'},
        {label: this.$t('所属租户'), prop: 'adminUserName', align: "center", isHide: !this.$permiss[454]},
      ],
    }
  },
  mounted() {
    //获取下拉渠道列表
    this.getChannels();
    //获取黑名单列表
    this.getTableData();
    //获取租户列表
    selectTenant().then(res => {
      this.tenantList = res.data
    });
  },
  methods: {
    //获取下拉渠道列表
    async getChannels() {
      const res = await selectChannelName()
      if (res.code === 1) {
        this.channelList = res.data
      }
    },
    //获取白名单列表
    async getTableData() {
      const [startTime, endTime] = dateFormatSection(this.page.timeValue);
      const params = {
        ...this.page,
        startTime, endTime
      }
      delete params.timeValue;
      this.loading = true
      const res = await fetchWhitelistList(params);
      if (res.code === 1) {
        const {list, total} = res.data;
        const toStr = (value) => {
          const len = value.length - 4
          let str = ''
          for (let i = 0; i < len; i++) {
            str += "*"
          }
          return str
        }
        this.tableData = list.map(item => {
          item.phone = toStr(item.phone) + item.phone.substr(item.phone.length - 4, 4)
          item.card = toStr(item.card) + item.card.substr(item.card.length - 4, 4)
          return item
        })
        this.page = Object.assign({}, this.page, {
          total: total,
        })
        this.loading = false
      } else {
        this.loading = false
      }
    },
    //重置
    resetData() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      };
      this.getTableData()
    },
    //下载模版
    async downLoanModel() {
      //白名单模版链接
      //http://yundun.diandianhuikj.com/whitelist_stencil.xlsx
      //黑名单链接
      //http://yundun.diandianhuikj.com/blacklistMode.xlsx
      // let url = ''
      // if (process.env.NODE_ENV === "development"){
      //     url = 'http://yundun.diandianhuikj.com'
      // } else {
      // }
      let eleLink = document.createElement('a')
      eleLink.download = '';
      eleLink.href = 'https://ddhkapps.oss-cn-hongkong.aliyuncs.com/yundun_template/whitelist_template.xlsx'
      eleLink.click()
      eleLink.remove()
    },
    //上传前
    beforeAvatarUpload(file) {
      const isFormat = '.xls||.xlsx';
      //获取最后一个.的位置
      const fileLastPostfix = file.name.lastIndexOf(".");
      //截取后缀名
      const fileNewName = file.name.substring(fileLastPostfix, file.name.length);
      //是否包含
      let isContains = isFormat.indexOf(fileNewName);
      // console.log("是否包含： " + isFormat.indexOf(fileNewName) > -1);
      if (isContains === -1) {
        this.$message.error(this.$t('文件格式不正确!'));
      }
      return isContains !== -1
    },
    //自定义上传白名单
    async uploadChange(data) {
      const formData = new FormData();
      formData.append('file', data.file);
      const res = await addWhiteListCsv(formData);
      if (res.code === 1) {
        this.$message.success(this.$t('上传成功'))
        this.getTableData()
      }
      // else if (res.code === 2) {
      //   this.uploadDialog(res.message);
      // }
      this.$refs.upload.clearFiles()
    },
    //去除重复
    async clearRepeat(data) {
      const formData = new FormData();
      formData.append('file', data.file);
      if (this.page.channelName) {
        formData.append('channelName', this.page.channelName)
      }
      const res = await selectRepeatWhitelist(formData, {responseType: 'blob'});
      const blob = new Blob([res]);
      const blobUrl = window.URL.createObjectURL(blob);
      const downloadLink = document.createElement('a');
      downloadLink.href = blobUrl;
      downloadLink.setAttribute('download', `${this.$t('报表')}.xls`);
      downloadLink.click();
      window.URL.revokeObjectURL(blobUrl);
      this.$refs.upload.clearFiles()
    },
    uploadDialog(content) {
      this.$confirm(content, this.$t('提示'), {
        confirmButtonText: this.$t('确认'),
        // cancelButtonText: this.$t('取消'),
        showCancelButton: false,
        type: 'warning'
      })
    },
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getTableData()
    },
  }
}
</script>

<style lang="less" scoped>
.upButtonBg {
  display: flex;
  text-align: right;
  align-items: center;
  justify-content: flex-end;
  padding-bottom: 10px;
}
</style>
